//参考https://forum.cocos.org/t/topic/62296/25
let loadingNode = null;
module.exports = {
  getLoadingScene: async () => {
    let scene = new cc.Scene();
    //1.增Canvas组件
    let root = new cc.Node("root");
    let canvas = root.addComponent(cc.Canvas);
    canvas.designResolution = new cc.size(750, 1334);
    root.parent = scene;

    let spriteNode = new cc.Node("bg");
    let sprite = spriteNode.addComponent(cc.Sprite);
    sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM;
    spriteNode.parent = root;
    spriteNode.width = canvas.designResolution.width;
    spriteNode.height = canvas.designResolution.height;
    spriteNode.setSiblingIndex(-1);
    // let labelNode = new cc.Node();
    // let label = labelNode.addComponent(cc.Label);
    // label.string = "Loading...";
    // labelNode.parent = spriteNode;

    await new Promise((resolve, reject) => {
      cc.resources.load("/loading/bg", (error, data) => {
        if (error) {
          cc.warn(error);
          reject(error);
        } else {
          sprite.spriteFrame = data;
          resolve();
        }
      });
    });

    await new Promise((resolve, reject) => {
      cc.resources.load("/prefab/progressBar", (error, data) => {
        if (error) {
          cc.warn(error);
          reject(error);
        } else {
          loadingNode = cc.instantiate(data);
          loadingNode.parent = root;
          loadingNode.scale = cc.winSize.width * 0.9 / loadingNode.width;
          loadingNode.setPosition(
            -loadingNode.width / 2 * loadingNode.scale,
            0
          );
          resolve();
        }
      });
    });

    return scene;
  },

  loadinglaunchScene: function(launchScene) {
    cc.director.preloadScene(
      launchScene,
      (completedCount, totalCount, item) => {
        loadingNode.getComponent("loading").progress = parseInt(
          completedCount / totalCount * 100
        );
      },
      error => {
        if (error) {
          console.log("==preloadScene error==", launchScene, error);
        }
        cc.director.loadScene(launchScene, null, function() {
          console.log("Success to load scene: " + launchScene);
        });
      }
    );
  }
};
